<template>
  <div class="todo-container">
    <h1>待办事项</h1>
    <TodoHeader @submit-todo="receiveTodo" />
    <TodoMain
      :todo-list="todoListShow"
      @delete-todo="handleDelete"
      @toggle-todo="handleToggle"
      @edit-todo="handleEdit"
    />
    <TodoFooter :count="todoListShow.length" @filter-todo="handleFilter" />
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import TodoFooter from './TodoFooter.vue'
import TodoHeader from './TodoHeader.vue'
import TodoMain from './TodoMain.vue'

// 初始化时从localStorage获取数据
const todoList = ref([])
const typeString = ref('all')

// 在组件挂载时从localStorage加载数据
onMounted(() => {
  const savedTodos = localStorage.getItem('qvtu-todo')
  if (savedTodos) {
    try {
      todoList.value = JSON.parse(savedTodos)
    } catch (e) {
      console.error('Failed to parse saved todos:', e)
      todoList.value = []
    }
  }
})

const receiveTodo = (newTodoItem) => {
  todoList.value.push(newTodoItem)
  // 立即保存到 localStorage
  localStorage.setItem('qvtu-todo', JSON.stringify(todoList.value))
}

const handleDelete = (index) => {
  todoList.value.splice(index, 1)
}

const handleToggle = (index) => {
  todoList.value[index].completed = !todoList.value[index].completed
}

const handleEdit = ({ index, todo }) => {
  todoList.value[index] = todo
}

const todoListShow = computed(() => {
  switch (typeString.value) {
    case 'not-complete':
      return todoList.value.filter((item) => !item.completed)
    case 'completed':
      return todoList.value.filter((item) => item.completed)
    default:
      return todoList.value
  }
})

const handleFilter = (type) => {
  typeString.value = type
}

// 监听todoList的变化，保存到localStorage
watch(
  todoList,
  (newValue) => {
    localStorage.setItem('qvtu-todo', JSON.stringify(newValue))
  },
  { deep: true }
)
</script>

<style scoped>
.todo-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

h1 {
  text-align: center;
  margin-bottom: 30px;
  color: #409eff;
}
</style>
